/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;
import entity.Account;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
/**
 *
 * @author Young Ran
 */
public class AccountDAO {
        private Connection cn;
        private CallableStatement cs;
        
    public AccountDAO() {
        cn = DB_Util.getConnection();
    }
    
    private ArrayList<Account> getAccountData(ResultSet rs) throws SQLException {
        ArrayList<Account> list = new ArrayList<Account>();
        while (rs.next()) {
            Account e = new Account();
            e.setUsername(rs.getString("AccountUsername"));
            e.setPassword(rs.getString("AccountPassword"));
            e.setLevel(rs.getInt("AccountLevel"));
            list.add(e);
        }
        return list;
    }
    
    //DISPLAY ACCOUNT:
    public ArrayList<Account> getAllAccount() throws SQLException {
        cs = cn.prepareCall("{call SP_Display_Account}");
        ResultSet rs = cs.executeQuery();
        return getAccountData(rs);
    }
    
    public ArrayList<Account> getByUName(String username) throws SQLException
    {
        cs = cn.prepareCall("{call SP_Search_Account(?)}");
        cs.setString(1, username);
        ResultSet rs = cs.executeQuery();
        return getAccountData(rs);
    }
    
    public void addAccount(Account item) throws SQLException
    {
        cs = cn.prepareCall("{call SP_Add_Account(?,?)}");
        cs.setString(1, item.getUsername());
        cs.setString(2, item.getPassword());
        cs.execute();
    }
    
    public void editAccount(Account item) throws SQLException{
        cs = cn.prepareCall("{call SP_Edit_Account(?,?)}");
        cs.setString(1,item.getUsername());
        cs.setString(2, item.getPassword());
        cs.execute();
    }
    
    public void promoteAccount(String username,int level) throws SQLException
    {
        cs = cn.prepareCall("{call SP_Promote_Account(?,?)}");
        cs.setNString(1,username);
        cs.setInt(2,level);
        cs.execute();
    }
}
